package com.lanou.hotel.controller;

import com.lanou.hotel.utils.PhotoUtil;
import com.lanou.hotel.vo.ResultVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.Inet4Address;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author msy
 * @since 2023-10-28
 */
@RestController
public class ImageController {

    @Value("${server.port}")
    private int port;

    /**
     * 上传图片
     * @return
     */
    @PostMapping("/image/uploadImg")
    public ResultVO<Map<String,String>> uploadImg(@RequestParam("file") MultipartFile file){
        try {
            //获取项目根路径
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/images/";

            Map<String, String> image = PhotoUtil.outputPhoto(file, realPath);

            //拼接图片路径
            String url = "http://localhost:" + port + "/images/" + image.get("imageName");
            String path = image.get("finalPath");
            image.put("url",url);
            image.put("path",path);

            return ResultVO.success("上传成功",image);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除图片
     * @param imageInfo
     * @return
     */
    @PostMapping("/image/locDelImg")
    public ResultVO<String> locDelImg(@RequestBody Map<String,String> imageInfo){
        try {
            String url = imageInfo.get("url");
            String path = imageInfo.get("path");

            //创建该文件file对象
            File file = new File(path);

            if (file.exists()) {
                //删除文件
                file.delete();

                return ResultVO.success("删除图片成功",null);
            }

            return ResultVO.failed("删除文件失败，文件不存在");
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed("系统繁忙，请稍后重试");
    }
}
